How to load config data from JSON file in HelloWorld?

I create a new project in Cocos2d JS 3.0beta, and want load config date from JSON file at the init of program. Data can be load, but is loaded after I need to use data of it, though I put the loading code before using its data. How can I load JSON file and make sure the loading is complete? So I can use the parsed data normally? Just use HelloWorld as a example, please.

How can I load JSON file and avoid the situation that read the data from it before the file loaded completely?

Hi, camel_liu~
For examle , you can put your json file in res folder.
And use cc.loader in your code like:

cc.loader.loadJson("res/example.json",function(error, data){
    cc.log(data);// data is the json object
});
1 Like

I’m using cocos2d-js v3.0beta.

I have tried cc.loader.loadJson like below:

cc.loader.loadJson(res.Config_json, function(err, data){
	if (err) {
		return cc.log("load failed");
	} else {
		cc.log("config: " + data);// data is the json object
		self.config = data;
	}
});

It works in JSB, but has a delay in HTML5. In HTML5, the json file is loaded after other code need to read its data, which leads to such error of “Cannot read property 'stageCount' of null'”. If I use:

cc.loader.load(res.Config_json, function(results){
    self.config = results[0];
    cc.log("config.stageCount--->" + self.config.stageCount);
});

Then, it work well and has no delay in HTML5, but when compile for win32 using JSB, it report error: TypeError: self.config is null. It seems to be unable to load the JSON file using cc.loader.load in JSB.

cc.loader.load and cc.loader.loadJson act differently in HTML5 and JSB. What’s the problem? How can I deal with it? If I want to it work in both HTML5 and JSB, what can I do?

Thanks, i will test it.

Is there any alter method to use cc.loader.load and cc.loader.loadJson on different platform? For example, is there a global variable in js which indicate different platform, such as HTML5, Windows, Androidm etc., so we can choose different function according to the variable’s value?

1 Like

how can i do this?

cc.loader.loadJson("res/example.json",function(error, data){
    this.verts = data.shape;
});

i want to set shape’s vertices from json file

I found how to use json file.

cc.loader.loadJson(“res/mydata.json”,function(err,data){
if (err) {
return cc.log(“load failed”);
} else {
// data is the json object
var version=data[“version”];
var text=data[“text”];
cc.log(version+"\n"+text);
}
});

// this is my json file “mydata.json” looks …
{
“version”:“1.0”,
“text”:“this is some data.”
}

1 Like